
import json
from common import *

offset_Constant = 0

def getTags(table):
	tags=[]
	tagres = dbClient().query('show tag keys from {}'.format(table))
	items = tagres.items()
	obj = items[0][1]
	for k in obj:
		tags.append(k['tagKey'])
	#print(tags)
	return tags

#导出JSON格式
def exprotJson(tables=[]):
	for table in tables:
		print('export db table: {}'.format(table))
		tags = getTags(table)
		result=dbClient().query('select * from {} limit {} offset {}'.format(table, limitSize(), offset_Constant))
		f=None
		try:
			f = open('{}{}_{}.json'.format(outputDir(), table, currentTimeStr()), 'w+')
		except OSError:
			print('write table:{} error!'.format(table))
		else:
			datas = []		
			items = result.items()
			obj = items[0][1]
			for k in obj:
				data = {}
				data['measurement'] = table
				data['tags'] = {}
				data['time'] = k['time']
				del[k['time']]
				for tag in tags:
					data['tags'][tag] = k[tag]
					del[k[tag]]
				data['fields'] = k
				datas.append(data)
			d = json.JSONEncoder().encode(datas) # convert josn str
			f.write(d)
			f.close()

#导出SQL格式
def exportSql(tables=[]):
	for table in tables:
		result=dbClient().query('select * from {} limit {} offset {}'.format(table, limitSize(), offset_Constant))
		f=None
		try:
			f = open('{}{}_{}.text'.format(outputDir(),table, currentTimeStr()), 'w+')
		except OSError:
			print('write table:{} error!'.format(table))
		else:
			points = result.get_points(measurement=table)
			print(points)
			print('sql')
			f.close()

#导出CSV格式
def exportCsv(tables=[]):
	for table in tables:
		result=dbClient().query('select * from {} limit {} offset {}'.format(table, limitSize(), offset_Constant))
		f=None
		try:
			f = open('{}_{}.csv'.format(table, currentTimeStr()), 'w+')
		except OSError:
			print('write table:{} error!'.format(table))
		else:
			items = result.items();
			print(str(items))
			#points = result.get_points(measurement=table)
			#print(points)
			f.close()

#导出数据库
def dumpDB():
	tables = []
	if dbTables() == '':
		array = dbClient().get_list_measurements()
		for a in array:
			tables.append(a['name'])
	else:
		tables = dbTables().split(',')
	format = ioFormat()
	print('format:{}'.format(format))
	if format == 'json':
		exprotJson(tables)
		print('dump db end!')
		'''
	elif format == 'sql':
		exportSql(tables)
	elif format == 'csv':
		exportCsv(tables)
		'''

def main():
	if verifyArgv() == False:
		return
	if connectDB():
		dumpDB()
	
if __name__ == '__main__':
	main()